<%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>

<head>

<style type="text/css">
/* html { height: 100% } */
/* body { height: 100%; margin: 0; padding: 0 } */
/* #map { width: 90%; height: 90% } */
.infoWindowSpan{
	font-size:13px;
	margin:0px auto;
	width:100%;
	height:100%;
	display:block;
}

.infoWindowDiv{
	font-size:13;
	margin:0px auto;
	width:100%;
	height:100%;
	display:block;
}
</style>

<!-- //localhost -->
<script type="text/javascript" src="http://apis.daum.net/maps/maps3.js?apikey=ab0cedfb49b8f831b1b8a9bbcc7f14cc33caa9a5"></script>
<!-- qro.co.kr -->
<!-- <script type="text/javascript" src="http://apis.daum.net/maps/maps3.js?apikey=e4663b451681213ba8c1532193d8e4dfc772d2d7"></script> -->
<!-- http://http://lbs.qronet.co.kr/ -->
<!-- <script type="text/javascript" src="http://apis.daum.net/maps/maps3.js?apikey=f1b8556458901ba8e373808431434890534bd9f7"></script> -->

<script type="text/javascript">


	var _daumMap = this;
	
	var _nowState;
	var zoom;
	var distanceUnit = [];
	_daumMap.directionMarkerJSON={};
	_daumMap.directionData={};

	var _eventObj = {
			m120Center:{},
			m120Zoom:{}
	};
	
	var _listener = {
			m110Cnt:0,
			m120Cnt:0,
			m110Name:'',
			m120Name:''
	};

	var _markerObj={
			m110:[],
			m120:[]
	};
	
	var _infoWindow={
			m110:[],
			m120:[]
			
	};
	
	var showStatus={
		m110:null,
		m120:null
	};
	
	var _functionName=[];
	
	var _m110Window={};

	var finishedLoadLine = true;
	
	function mapInit_m120(mapSetting){
		//logs('mapInit_m120(mapSetting)');
// 		jsonLog(mapSetting);
		
		if(mapSetting.swLat){
			// ? LatLngBounds ?? ??
			var bounds = new daum.maps.LatLngBounds();
			
			bounds.extend(new daum.maps.LatLng(mapSetting.swLat, mapSetting.swLng));
			bounds.extend(new daum.maps.LatLng(mapSetting.neLat, mapSetting.neLng));

			try{
				var boundInterval = setInterval(function(){
					_daumMap.map.setBounds(bounds);
	 				//logs('boundInterval');
					window.clearInterval(boundInterval);
					
					},300);	
			}catch(e){}	
		}
		
		
		
		_daumMap.carcode = mapSetting['carcode'];
		_daumMap.noData = false;
// 		var position = new daum.maps.LatLng(37.455928, 126.886643);
// 		//logs('==========================');
// 		//logs(mapSetting['lat']);
// 		//logs(mapSetting['lng']);
// 		//logs('==========================');
		if(mapSetting['lat'].length==0 ||  mapSetting['lng'].length==0){
			mapSetting['lat']='37.455928';
			mapSetting['lng']='126.886643';
			_daumMap.noData = true;
		}
		var position = new daum.maps.LatLng(mapSetting['lat'], mapSetting['lng']);
		_daumMap.map = new daum.maps.Map(document.getElementById('map'), {
			center: position,
			level: 10,	// 줌 관련해서는 나중에... 왜냐면 브라우져의 크기도 계산해야 하는 부분이라서...
			mapTypeId: daum.maps.MapTypeId.ROADMAP
		});
		_daumMap.reload = true;
		zoom = _daumMap.map.getLevel();
	
	//  zoom 및 타입(지도, 스카이뷰) 컨트롤러 생성    
		var zoomControl = new daum.maps.ZoomControl();
		var mapTypeControl = new daum.maps.MapTypeControl();
		 
		_daumMap.map.addControl(zoomControl, daum.maps.ControlPosition.RIGHT);
		_daumMap.map.addControl(mapTypeControl, daum.maps.ControlPosition.TOPRIGHT);  
// 		daum.maps.event.addListener(_daumMap.map,"idle",waitingZoom);
		


		
		data['setting']={};
		
		distanceUnit.push( 20);
		distanceUnit.push( 30);
		distanceUnit.push( 50);
		distanceUnit.push( 100);
		distanceUnit.push( 250);
		distanceUnit.push( 500);
		distanceUnit.push( 1000);
		distanceUnit.push( 2000);
		distanceUnit.push( 4000);
		distanceUnit.push( 8000);
		distanceUnit.push( 16000);
		distanceUnit.push( 32000);
		distanceUnit.push( 64000);
		distanceUnit.push( 128000);
		
		if(!_daumMap.noData){
			getMapLine('center');	
			
		}
	
		daum.maps.event.addListener(_daumMap.map, 'zoom_changed', function(){
			drawMarkerM120();
		});
	}
	function followPopup(obj){
		//logs('followPopup(obj)');	
	
		try{
			daum.maps.event.removeListener(_daumMap.map, 'center_changed', function(){
				listenerFunction(obj);
			});
		}catch(e){
			//logs('followPopup(obj){ cannot remove Listner!!');
			logs(e);
		}
		_listener.m120Name = 'm120Listener'+_listener.m120Cnt++;
		//logs('_listener.m120Name = '+_listener.m120Name);
		daum.maps.event.addListener(_daumMap.map, 'center_changed', setListenerFunc(_listener.m120Name , obj));
		window[_listener.m120Name]();
		
	}
		
	function followPopupM110(obj){
		
		logs('followPopupM110(');
		logs($(obj));
		try{
			daum.maps.event.removeListener(_daumMap.map, 'center_changed', function(){
// 				listenerFunction(obj);
			});
		}catch(e){
			//logs('followPopup(obj){ cannot remove Listner!!');
			logs(e);
		}
		_listener.m110Name = 'm110Listener'+_listener.m110Cnt++;
		logs('_listener.m110Name = '+_listener.m110Name);
		daum.maps.event.addListener(_daumMap.map, 'center_changed', setListenerFunc2(_listener.m110Name , obj));
		_m110Window[_listener.m110Name]();
		$('#carInfo').show();
		
	}
		


	function setListenerFunc2(name, obj){
		logs('setListenerFunc2(name, obj){');
		_m110Window[name] = function(){
			
			changePopupPositionM110(obj);			
					
		}
		return _m110Window[name];
	}	
	
	
	function hideM120CarInfo(){
		$('#carInfoPopup').hide();
		if(carInfoObj.infoTag){
			$(carInfoObj.infoTag).remove();
		}
		showStatus.m120=null;
	}
		
	function hideM110CarInfo(){
		$('#carInfo').hide();
		if(carInfoObj.infoTag){
			$(carInfoObj.infoTag).remove();
		}
		showStatus.m110=null;
	}
	function changePopupPositionM110(obj){
		logs('changePopupPositionM110');
		var p1 = $(obj);
		var p2 = $(obj).parent().parent();
		
		if(!showStatus.m110) return;
		try{
			try{
				
				if(carInfoObj.infoTag){
					$(carInfoObj.infoTag).remove();
				}
				
				var width = $('#carInfo').css('width');
				var height = $('#carInfo').css('height');
				width = width.replace('px','');
				height = height.replace('px','');
				width*=1;
				height*=1;
				
				var left = p1.position().left +p2.position().left;
				var top = p1.position().top  +p2.position().top;
				
				var leftSide = $('.panel_left_content').width()+$('.button_left').width()-15;
				var topSide = $('.headerContent').height()+$('.topInfo').height();
				
				if(getBtnLeft()){
					leftSide=25;
				}
				
				if(getWideIcon()){
					leftSide=0;
					topSide=0;
				}
				logs('leftSide - '+leftSide);
				logs('topSide-'+topSide);
				logs('(left-width/2) = '+(left-width/2));
				logs('(top-height) = '+(top-height));
				$('#carInfo').attr('position','absolute');
				$('#carInfo').attr('z-index','2');
				$('#carInfo').css('left', (left+leftSide-width/2)+'px');
				$('#carInfo').css('top', (top+topSide-height)+'px');
				$('#carInfo').show();
				return;
			}catch(e){logs(e)}
			finally{return;};
			
			
		}catch(e){
			//logs(name);
			//logs(131);
			logs(e);
			
			try{
				daum.maps.event.removeListener(_daumMap.map, 'center_changed', _m110Window[name]);
			}catch(e){
				//logs('window[name]');
				logs(e);
			}
		}	
	
	}

	function setListenerFunc(name, obj){
		//logs('setListenerFunc(name, obj){');
		window[name] = function(){
			//logs('listenerFunction');
			changePopupPositionM120(obj);			
		}
		return window[name];
	}
		
		
	function changePopupPositionM120(obj){
		logs('changePopupPositionM120(');
		if(!showStatus.m120) return;
		
		var p1 = $(obj);
		var p2 = $(obj).parent().parent();
		try{
			try{
				logs(1);
				if(carInfoObj.infoTag){
					$(carInfoObj.infoTag).remove();
				}
				logs(2);

				var width = $('#carInfoPopup').css('width');
				var height = $('#carInfoPopup').css('height');
				width = width.replace('px','');
				height = height.replace('px','');
				width*=1;
				height*=1;
				
				var left = p1.position().left +p2.position().left;
				var top = p1.position().top  +p2.position().top;
				
				var leftSide = $('.panel_left_content').width()+$('.button_left').width()-15;
				var topSide = $('.headerContent').height()+$('.topInfo').height();
				
				if(getBtnLeft()){
					leftSide=25;
				}
				
				if(getWideIcon()){
					leftSide=0;
					topSide=0;
				}
				logs("getWideIcon() = "+getWideIcon());
				logs('leftSide - '+leftSide);
				logs('topSide-'+topSide);
				logs('(left-width/2) = '+(left-width/2));
				logs('(top-height) = '+(top-height));
				$('#carInfoPopup').attr('position','absolute');
				$('#carInfoPopup').attr('z-index','2');
				$('#carInfoPopup').css('left', (left+leftSide-width/2)+'px');
				$('#carInfoPopup').css('top', (top+topSide-height)+'px');
				$('#carInfoPopup').show();
				return;
			}catch(e){logs(e)}
			finally{return;};
			
			
		}catch(e){
			//logs(name);
			//logs(131);
			logs(e);
			
			try{
				daum.maps.event.removeListener(_daumMap.map, 'center_changed', _m110Window[name]);
			}catch(e){
				//logs('window[name]');
				logs(e);
			}
		}	
	
		try{
			
			
			
			var areaLeft = $(obj).parent().parent().css('left');
			var areaTop = $(obj).parent().parent().css('top');
			areaLeft = areaLeft.replace('px','');
			areaTop = areaTop.replace('px','');
			areaLeft*=1;
			areaTop*=1;
			

			logs('areaLeft = '+areaLeft);
			logs('areaTop = '+areaTop);
			
			var parentLeft = $(obj).parent().parent().parent().parent().css('left');
			var parentTop = $(obj).parent().parent().parent().parent().css('top');
			
			logs($(obj));
			logs($(obj).parent());
			logs($(obj).parent().parent());
			logs($(obj).parent().parent().parent());
			
			if(parentLeft=='auto'){
				
			
				moveToLittle();
				
				
				changePopupPositionM120(obj);
				
				
				 
				return;
			
			}
			
			logs('parentLeft = '+parentLeft);
			logs('parentTop = '+parentTop);
			
			parentLeft = parentLeft.replace('px','');
			parentTop = parentTop.replace('px','');
			


			logs('parentLeft = '+parentLeft);
			logs('parentTop = '+parentTop);
			
			parentLeft*=1;
			parentTop*=1;
			

			logs('parentLeft = '+parentLeft);
			logs('parentTop = '+parentTop);
			
			
			var width = $('#carInfoPopup').css('width');
			var height = $('#carInfoPopup').css('height');
			width = width.replace('px','');
			height = height.replace('px','');
			width*=1;
			height*=1;

			logs('width = '+width);
			logs('height = '+height);
			
			var mapTop = $('.map').css('top');
			var mapLeft = $('.map').css('left');
			logs('mapTop = '+mapTop);
			logs('mapLeft = '+mapLeft);
			
			mapTop = mapTop.replace('px','');
			mapLeft = mapLeft.replace('px','');
			mapTop*=1;
			mapLeft*=1;
			
			logs('set left = '+(parentLeft+areaLeft+mapLeft-(width/2)));
			logs('set top = '+(parentTop+areaTop+mapTop-height-0));
			
//				$('#carInfo').css('left',(parentLeft+areaLeft+mapLeft-(width/2))).css('top',(parentTop+areaTop+mapTop-height-0));
			$('#carInfoPopup').css('left',(parentLeft+areaLeft+mapLeft-(width/2))).css('top',(parentTop+areaTop+mapTop-height-0));
		}catch(e){
			logs(name);
			logs(131);
			logs(e);
			
			try{
				daum.maps.event.removeListener(_daumMap.map, 'center_changed', window[name]);
			}catch(e){
				logs('window[name]');
				logs(e);
			}
		}
	}
	
	function removeCarDetailDialogM120(){
		try{
			//logs('aaaaaaaaaaaaa');
			if(typeof window[_listener.m120Name] != 'undefined'){
				daum.maps.event.removeListener(_daumMap.map, 'center_changed', window[_listener.m120Name]);	
			}else{
				//logs('안탔다.');
			}
			
		}catch(e){
			logs('window['+_listener.m120Name+']');
			logs(e);
		}
	}
	
	function makeMapCenter_m110(mapSetting){
		var position = new daum.maps.LatLng(mapSetting['lat'], mapSetting['lng']);
		if(outOfKoreaRange(mapSetting['lat'], mapSetting['lng'])){
			position = new daum.maps.LatLng(37.455928, 126.886643);
		}
		_daumMap.map = new daum.maps.Map(document.getElementById('map'), {
			center: position,
			level: mapSetting['zoom'],	// 줌 관련해서는 나중에... 왜냐면 브라우져의 크기도 계산해야 하는 부분이라서...
			mapTypeId: daum.maps.MapTypeId.ROADMAP
		});
	}
	
	function mapInit_m110(mapSetting) {
		//logs('mapInit_m110(mapSetting) {');
// 		var position = new daum.maps.LatLng(37.455928, 126.886643);
		logs("mapSetting['lat'] = "+mapSetting['lat']+", mapSetting['lng'] = "+mapSetting['lng']);
		
		makeMapCenter_m110(mapSetting);
		
// 		var position = new daum.maps.LatLng(mapSetting['lat'], mapSetting['lng']);
// 		if(outOfKoreaRange(mapSetting['lat'], mapSetting['lng'])){
// 			position = new daum.maps.LatLng(37.455928, 126.886643);
// 		}
// 		_daumMap.map = new daum.maps.Map(document.getElementById('map'), {
// 			center: position,
// 			level: 10,	// 줌 관련해서는 나중에... 왜냐면 브라우져의 크기도 계산해야 하는 부분이라서...
// 			mapTypeId: daum.maps.MapTypeId.ROADMAP
// 		});
	
		zoom = _daumMap.map.getLevel();
		
		distanceUnit.push( 20);
		distanceUnit.push( 30);
		distanceUnit.push( 50);
		distanceUnit.push( 100);
		distanceUnit.push( 250);
		distanceUnit.push( 500);
		distanceUnit.push( 1000);
		distanceUnit.push( 2000);
		distanceUnit.push( 4000);
		distanceUnit.push( 8000);
		distanceUnit.push( 16000);
		distanceUnit.push( 32000);
		distanceUnit.push( 64000);
		distanceUnit.push( 128000);
		//logs('finish init');
		
		// 중심좌표 이동시
		daum.maps.event.addListener(_daumMap.map, 'center_changed', function(){
			changeDialogPopup();
		});	
		
		daum.maps.event.addListener(_daumMap.map, 'zoom_changed', function(){
			changeDialogPopup();
		});
		

		
		//  zoom 및 타입(지도, 스카이뷰) 컨트롤러 생성    
		var zoomControl = new daum.maps.ZoomControl();
		var mapTypeControl = new daum.maps.MapTypeControl();
		 
		_daumMap.map.addControl(mapTypeControl, daum.maps.ControlPosition.TOPRIGHT);
		_daumMap.map.addControl(zoomControl, daum.maps.ControlPosition.RIGHT);  
		
	};
	
	function changeDialogPopup(){
		//logs('changeDialogPopup(){');
		try{
			var areaLeft = $('area')[selectedCar].parentNode.parentNode.style.left;
			var areaTop = $('area')[selectedCar].parentNode.parentNode.style.top;
			areaLeft = areaLeft.replace('px','');
			areaTop = areaTop.replace('px','');
			areaLeft*=1;
			areaTop*=1;
			
			var parentLeft = $('area')[selectedCar].parentNode.parentNode.parentNode.parentNode.style.left;
			var parentTop = $('area')[selectedCar].parentNode.parentNode.parentNode.parentNode.style.top;
			
			
			parentLeft = parentLeft.replace('px','');
			parentTop = parentTop.replace('px','');
			parentLeft*=1;
			parentTop*=1;
			
			var width = $('#carInfo').css('width');
			var height = $('#carInfo').css('height');
			width = width.replace('px','');
			height = height.replace('px','');
			width*=1;
			height*=1;
			
			$('#carInfo').css('left',(parentLeft+areaLeft-(width/2))).css('top',(parentTop+areaTop-height-0));
		}catch(e){
			
			logs('changeDialogPopup()');
			logs(e);
		}
		
	}
	
	function changeMapLine(carCode){
		//logs('changeMapLine(carCode){');
	
		_daumMap.carcode = carCode;
		_daumMap.noData = false;
		_daumMap.reload = true;
		getMapLine('reload');
		drawLine();
	}
	var data={};
	
	var index=0;
	var lineArray=[];
	var markerArray=[];
	var markerArrayIndex={};
	var lastMakerLatLng=[];
	var bindIdle = false;
	var lastPosition={};
	
	var _this = this;
	_this.lines=[];	// 지도 라인 배열. 삭제 할 때 쓰인다.
	
	
	
	/**
	1. 처음 들어 왔을 때,
	2. 전체차량 보기에서 사용자 변경
	3. 날짜 변경
	4. 위치 추적 on 
	
	이 곳을 탄다.
	*/
	function drawLine(){
		clearLines();
		var options={};
		options['endArrow']=true;	
		var line = new daum.maps.Polyline(options);
		var path = [];
		
		var url = '/map/getCarRoute.json';
		var param = {
				carCode:_daumMap.carcode,
				date:getDatePickerDate()
		};
		
		
		AjaxPost(url, param, function(data){
			var lastLatLng=null, moveToCenter={};
			for(var i=0;i<data.list.length;i++){
				var arr = data.list[i];
				for(var j=0;j<arr.length;j++){
					if(outOfKoreaRange(arr[j].lat, arr[j].lng)) continue;
					
// 					if(i==0&&j==0){	//센터 맞추기
						moveToCenter.lat = arr[j].lat;
						moveToCenter.lng = arr[j].lng;
// 					}
					if(lastLatLng && j==0){
						drawNoDataLine(lastLatLng, new daum.maps.LatLng(arr[j].lat,arr[j].lng));
					}
					lastLatLng=new daum.maps.LatLng(arr[j].lat,arr[j].lng);
					path.push(lastLatLng);
				}
				line.setPath(path);
				line.setMap(_daumMap.map);
				_this.lines.push(line);
				path = [];
				line = new daum.maps.Polyline(options);
				
			}
			moveMapTo(moveToCenter.lat, moveToCenter.lng);	
		});
	}
	
	// 
	function drawNoDataLine(latLng1, latLng2){
		var options={
				strokeColor:'#e10000',
				fillColor:'#0000f1',
				strokeWeight:5 ,
				strokeOpacity :0.3
		};
		var line = new daum.maps.Polyline(options);
		var path = [];
		path.push(latLng1);
		path.push(latLng2);
		line.setPath(path);
		line.setMap(_daumMap.map);
		_this.lines.push(line);
	}
	
	
	function getMapLine(type){
		
		return;
		
		if(!finishedLoadLine) return;	
		//logs('getMapLine(='+type);
		if(type=='center'){
			try{
// 				window.clearInterval(_eventObj.m120Center);
			}catch(e){}
		}else if(type=='zoom'){
			try{
// 				window.clearInterval(_eventObj.m120Zoom);	
			}catch(e){}
		}
		if(_daumMap.reload){
			
				//logs('if(_daumMap.reload){');
				hideCarInfoPopup();
				clearLines();
				
				lastMakerLatLng[0]=0;
				lastMakerLatLng[1]=0;
				markerArrayIndex={};
				
				index=0;
				lineArray=[];
				
				markerArrayIndex={};
				bindIdle = false;
				lastPosition={};
				
			}
		
		lastMakerLatLng[0]=0;
		lastMakerLatLng[1]=0;
		var url="getCarInfoList.json";
		
		if(!bindIdle){
			
			daum.maps.event.addListener(_daumMap.map, 'dragend', function(){
				
					getMapLine('center');
				
			});	
			
			
			daum.maps.event.addListener(_daumMap.map, 'zoom_changed', function(){
					getMapLine('zoom');
			});	
			
			bindIdle = true;
		}
		
		

		var param = {};

		if(type=='zoom'){
			
		}
		
		zoom = _daumMap.map.getLevel();
		param['zoom'] = _daumMap.map.getLevel();
		param['carCode'] = _daumMap.carcode;
		param['swLat'] = _daumMap.map.getBounds().getSouthWest().getLat();
		param['swLng'] = _daumMap.map.getBounds().getSouthWest().getLng();
		param['neLat'] = _daumMap.map.getBounds().getNorthEast().getLat();
		param['neLng'] = _daumMap.map.getBounds().getNorthEast().getLng();
		
		param.secPeriod = $('#getPeriod').val();
		
		param.date = getDatePickerDate();
		
		
		finishedLoadLine = false;
		AjaxPost(url, param, function(data){
			
// 			jsonLog(data);
			
			var options={};
			options['endArrow']=true;			
			
			var line = new daum.maps.Polyline(options);
			line.setMap(null);
			var path = [];
			var size = data.carInfo.length;

			clearLines();
			
			
			var lastLatLng={
					lat:0,
					lng:0
			};
			var tooFar = false;
			
			logs('data.carInfo.length = '+data.carInfo.length);
			$.each(data.carInfo,function(index, value){
				
				if(outOfKoreaRange($(value)[0]['lat'], $(value)[0]['lng'])) return true;	// continue			
				
				if(_daumMap.reload){
					var position = new daum.maps.LatLng($(value)[0]['lat'], $(value)[0]['lng']);
					_daumMap.reload = false;
					
					if(typeof setPaging=='function'){
						setPaging(data);
					}

				}
				if(lastLatLng.lat>0){
					if(getDistanceFromLatLngInKm(lastLatLng.lat, lastLatLng.lng, $(value)[0]['lat'], $(value)[0]['lng'])>distanceUnit[zoom]*5){
// 						logs('zoom = '+zoom);
						if(zoom>3)  tooFar = true;
						logs('too far!!!');
					}
				}
				if(!tooFar){
					path.push(new daum.maps.LatLng($(value)[0]['lat'], $(value)[0]['lng']));
					line.setPath(path);
				}
								
				
				if(line.getLength()>distanceUnit[zoom]*2 || index == 1 || (index==(size-1)) || tooFar){
					
					line.setMap(_daumMap.map);
					lineArray.push(line);
					line = new daum.maps.Polyline(options);
					path = [];
					path.push(new daum.maps.LatLng($(value)[0]['lat'], $(value)[0]['lng']));
					
				}
// 				if(tooFar){
// 					path.push(new daum.maps.LatLng($(value)[0]['lat'], $(value)[0]['lng']));
// 				}



				lastLatLng.lat =$(value)[0]['lat'];
				lastLatLng.lng= $(value)[0]['lng'];
				tooFar = false;
			});
			if(type=='zoom'){
				drawMarkerM120();
			}
			
			finishedLoadLine=true;			

			
			options={};
			line = null;
			path = [];
			size = null;
			
		});
	}
	
	function moveMapTo(lat, lng){
		
		if(outOfKoreaRange(lat, lng)) return;
		
		logs('moveMapTo lat='+lat+', lng='+lng);

		var latLng = new daum.maps.LatLng(lat, lng);
		var isInBound = null; 
		try{
			isInBound = isInBounds(latLng);
		}catch(e){
			logs('moveMapTo error1');
			logs(e);
		}
		
		try{
			_daumMap.map.setCenter(latLng);	
		}catch(e){
			logs('moveMapTo error2');
			logs(e);
		}
			
		
		return isInBound;
	}
	
// 	위치가 현재 바운더리 안에 있는지 체크. 
// 	벗어나면 return false
// 	안이면 return true;
	function isInBounds(latLng){
		logs('isInBounds');
		if(outOfKoreaRange(latLng.getLat(), latLng.getLng())) return false;
		
		var minLat = _daumMap.map.getBounds().getSouthWest().getLat();
		var minLng = _daumMap.map.getBounds().getSouthWest().getLng();
		var maxLat = _daumMap.map.getBounds().getNorthEast().getLat();
		var maxLng = _daumMap.map.getBounds().getNorthEast().getLng();
		
		if(latLng.getLat() < minLat || latLng.getLat() > maxLat) return false;
		if(latLng.getLng() < minLng || latLng.getLng() > maxLng) return false;
		return true;
	}
	
	function moveToLittle(){
		
		
		_daumMap.map.setCenter(_daumMap.map.getCenter());
		
	}
	
	function getDaumMapZoom(){
		//logs('getDaumMapZoom(){');
		return _daumMap.map.getLevel();
	}
	
	function setDaumMapZoom(zoom){
		logs('setDaumMapZoom(zoom){'+zoom);
		if(zoom<1 || zoom>14) return;
		_daumMap.map.setLevel(zoom);
	}
	
	function drawMarkerM120(){
		
		if(_nowState == 'm110'){
			return;	
		}
		//logs('drawMarkerM120()');
		hideCarInfoPopup();
		
		var url='drawMarkerM120.json';
		
		markerSetting.paging.carCode = _daumMap.carcode;
		markerSetting.paging.zoom =  _daumMap.map.getLevel();
		
		
		markerSetting.paging['minLat'] = _daumMap.map.getBounds().getSouthWest().getLat();
		markerSetting.paging['minLng'] = _daumMap.map.getBounds().getSouthWest().getLng();
		markerSetting.paging['maxLat'] = _daumMap.map.getBounds().getNorthEast().getLat();
		markerSetting.paging['maxLng'] = _daumMap.map.getBounds().getNorthEast().getLng();
		
		markerSetting.paging.date = getDatePickerDate();		
		
		var param=markerSetting.paging;
		
		AjaxPost(url, param, function(data){
			
			//logs('drawMarkerM120()========================');
			try{
				//logs('data.markers.length = '+data.markers.length);	
			}catch(e){}
			
			clearMarkers();
			
// 			logs('drawMarkerM120()========================');
			var length = data.markers.length;
			$.each(data.markers,function(index, value){
				markerArray.push(makeMarker($(value)[0], length- index, 'm120'));	
			});
			
			
		});
	
	
	}
	
	function clearLines(){
		logs('clearLines()');
		while(_this.lines.length>0){
			var line = _this.lines.pop();
			line&&line.setMap(null);
		}
		_this.lines=[];
	}
	
	function clearMarkers(){
		logs('clearMarkers()');

		if(markerArray.length>0){
			while(markerArray.length>0){
				var marker = markerArray.pop();
				try{
					daum.maps.event.removeListener(marker, 'click', function(){});	
				}catch(e){
					logs('remove marker click listener');
					logs(e);
				}
				try{
					daum.maps.event.removeListener(marker, 'dragstart', function(){});	
				}catch(e){
					logs('remove marker dragstart listener');
					logs(e);
				}
				
				
				marker.setMap(null);
			}
		}
		markerArray=[];
		
	}
	
	var markerPositions=[];	
	
	function makeMarkerM110(data, ind, option){
		jsonLog(data);
		//logs('makeMarker(data, ind, option){ = '+ind+', option = '+option);
		var marker_icon = new daum.maps.MarkerImage(
				'${imgUrl}/nowPosition.png',
				new daum.maps.Size(25, 49),
				new daum.maps.Point(12.5,24.5),
				"poly",
				"1,20,1,9,5,2,10,0,21,0,27,3,30,9,30,20,17,33,14,33"
			);
		
		var marker_options = {
			position: new daum.maps.LatLng(data.lat, data.lng),
			image: marker_icon,
		                    title: data.name,
		                    zIndex:'2'
		                    };
		var marker = new daum.maps.Marker(marker_options);
		marker.setMap(_daumMap.map);
	
		_daumMap.directionMarkerJSON[data.seq]=marker;
		_daumMap.directionData[data.seq]=data;
		
		var funcName = 'clickListner'+data.seq;
// 		setFunc(funcName);
		setFunc2(funcName, marker, data.carCode, data.seq);
		
		try{
			if(option == 'm110'){
				
				var infowindow = new daum.maps.InfoWindow({
					content: '<span class="infoWindowSpan"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'+data.content+'</span>'
					,removable : true
				});
					
				infowindow.open(_daumMap.map, marker);
				_infoWindow.m110.push(infowindow);	
				daum.maps.event.addListener(marker, 'click', _m110Window[funcName]);	
			}
			
				
		}catch(e){}
		
		
		return marker;
			
	}
		
	function makeMarker(data, ind, option){
		jsonLog(data);
		logs('makeMarker(data, ind, option){ = '+ind+', option = '+option+', data.cardinal = '+data.cardinal);
		var cardinal = data.cardinal*1;
		var iconImage = '${imgUrl}/nowPosition.png';
		
		var marker_icon = new daum.maps.MarkerImage(
				iconImage,
				new daum.maps.Size(25, 49),
				new daum.maps.Point(12.5,24.5),
				"poly",
				"1,20,1,9,5,2,10,0,21,0,27,3,30,9,30,20,17,33,14,33"
			);
		
		if(cardinal>=0){
			if(cardinal<10){
				cardinal='0'+cardinal;
			}
			iconImage = '/resources/images/cars/direction_arrow_'+cardinal +'.png';
			marker_icon = new daum.maps.MarkerImage(
					iconImage,
					new daum.maps.Size(22, 22),
					new daum.maps.Point(11,11),
					"poly",
					"1,20,1,9,5,2,10,0,21,0,27,3,30,9,30,20,17,33,14,33"
				);
		}
		
		var marker_options = {
			position: new daum.maps.LatLng(data.lat, data.lng),
			image: marker_icon,
		                    title: data.name,
		                    zIndex:'2'
		                    };
		var marker = new daum.maps.Marker(marker_options);
		marker.setMap(_daumMap.map);
	
		_daumMap.directionMarkerJSON[data.seq]=marker;
		_daumMap.directionData[data.seq]=data;
		
		var funcName = 'clickListner'+data.seq;
// 		setFunc(funcName);
		setFunc(funcName, marker, data);
		
		try{
			
			if(typeof option != 'undefined' && option == 'now'){
// 				jsonLog(data);
				
				//logs('info data.detectTime/1000 = '+data.detectTime/1000);
				var infowindow = new daum.maps.InfoWindow({
					content: '<span class="infoWindowSpan"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'+formatter.timeFormatHHMMSS2nd(data.detectTime/1000)+'</span>'
					,removable : true
				});
				//logs(infowindow);
				infowindow.setZIndex(2);	
				infowindow.open(_daumMap.map, marker);
				_infoWindow.m120.push(infowindow);
				daum.maps.event.addListener(marker, 'dragstart', window[funcName]);
				window[funcName]();
			}else{
				daum.maps.event.addListener(marker, 'click', window[funcName]);	
			}
		}catch(e){logs('makeMarker(data, ind, option) 1111');logs(e);}
		try{
			if(option == 'm110'){
				
				var infowindow = new daum.maps.InfoWindow({
					content: '<span class="infoWindowSpan"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'+data.content+'</span>'
					,removable : true
				});
					
				infowindow.open(_daumMap.map, marker);
				_infoWindow.m110.push(infowindow);	
			}
			
			if(option == 'm120'){
				return marker;
				
				var infowindow = new daum.maps.InfoWindow({
					content: '<span class="infoWindowSpan"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'+formatter.timeFormatHHMMSS2nd(data.detectTime)+'</span>'
					,removable : true
				});
				infowindow.setZIndex(2);	
				infowindow.open(_daumMap.map, marker);
				_infoWindow.m120.push(infowindow);	
			}
				
		}catch(e){}
		
		
		return marker;
	}
	
	var carInfoObj={
			x:0,
			y:0,
			infoTag:null
	}
	
	
	var syncPopupM110 = 0;
	function setFunc2(name, obj, carCode, seq){
		_functionName.push(name);
		_m110Window[name] = function(){
			var ind = name.substring('clickListner'.length, name.length);
			try{
				
// 				logs('$(obj)');
// 				logs($(obj));
// // 				carInfoObj.x = $(obj)[0]['Hd'].x;
// // 				carInfoObj.y = $(obj)[0]['Hd'].y;

				showStatus.m110=true;
				if(typeof obj == 'object'){
					followPopupM110($(obj)[0]['a']);
				}else{
					followPopupM110($(this)[0]['a']);	
				}
				logs('syncPopupM110 = '+syncPopupM110+', seq = '+seq);
				!(syncPopupM110==seq) && syncPopupDialog(carCode, seq);
				syncPopupM110 = seq;
			}catch(e){
				logs('setFunc2 - followPopup');
				logs(e);
			}
			
		}
	}
	function setFunc(name, obj, data){
		
		logs('setFunc(name, obj){');
		_functionName.push(name);
		
		window[name] = function(){
			var ind = name.substring('clickListner'.length, name.length);
			focusInPaging(ind);
			
			setCarInfoPopup(data);
			
// 			setCarInfoPopup(_daumMap.directionData[ind]);
			
			try{
				
// 				carInfoObj.x = $(obj)[0]['Hd'].x;
// 				carInfoObj.y = $(obj)[0]['Hd'].y;
				
				showStatus.m120=true;
				logs('typeof obj = '+typeof obj);
				if(typeof obj == 'object'){
					changePopupPositionM120($(obj)[0]['a']);
					followPopup($(obj)[0]['a']);
				}else{
					changePopupPositionM120($(this)[0]['a']);					
					followPopup($(this)[0]['a']);	
					
				}
				
					
			}catch(e){
				logs('setFunc - followPopup');
				logs(e);
			}
			
		};
	}

	
	function getCarInfos(){
// 		var url = 'map/';
// 		AjaxPost(url, param, function(data){
			
// 		});
	}
	_daumMap.markerJSON={};
	
	function changeCarPosition2(carList){
// 		jsonLog(carList);
		//logs('changeCarPosition2(carList)');
// 		var marker = _daumMap.markerJSON[carList['carCode']];
// 		marker.setPosition(new daum.maps.LatLng(carList['lat'], carList['lng']));
		makeMarker(carList,'','m110');
	}
	
	// m110
	function setCarPositionsInMap(){
		
		//logs('setCarPositionsInMap()');
	_daumMap.marker_icon = new daum.maps.MarkerImage(
			'${imgUrl}/nowPosition.png',
			new daum.maps.Size(22, 22),
			new daum.maps.Point(11,11),
			"poly",
			"1,20,1,9,5,2,10,0,21,0,27,3,30,9,30,20,17,33,14,33"
		);
	
		<c:forEach items="${carList }" var="car" varStatus="status">
			_daumMap.marker_options<c:out value="${status.count}"/> = {
				position: new daum.maps.LatLng(<c:out value="${car.lat}"/>, <c:out value="${car.lng}"/>),
				image: _daumMap.marker_icon,
			                    title: '<c:out value="${car.name}"/>',
			                    zIndex:'2'
			                    };
			var marker<c:out value="${status.count}"/> = new daum.maps.Marker(marker_options<c:out value="${status.count}"/>);
			marker<c:out value="${status.count}"/>.setMap(_daumMap.map);
		
			_daumMap.markerJSON['<c:out value="${car.carCode}"/>']=marker<c:out value="${status.count}"/>;
			
			daum.maps.event.addListener(marker<c:out value="${status.count}"/>, 'click', function handlerMarker<c:out value="${status.count}"/>(){
				
				//logs('handlerMarker');
				chooseCar('<c:out value="${car.carCode}"/>', '<c:out value="${status.count}"/>', false);				
			});
			
			
			_markerObj.m110.push(marker<c:out value="${status.count}"/>);
			
			try{
				
				
				
				var infowindow<c:out value="${status.count}"/> = new daum.maps.InfoWindow({
					content: '<span class="infoWindowSpan"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'+"<c:out value="${car.carRegiNumber}"/>"+'</span>'
				});
// 				infowindow.setZIndex(10);
				infowindow<c:out value="${status.count}"/>.open(_daumMap.map, marker<c:out value="${status.count}"/>);
				_infoWindow.m110.push(infowindow<c:out value="${status.count}"/>);
			}catch(e){logs('setCarPositionsInMap()11');logs(e);}
			
		</c:forEach>
		
		var position4bound=new Array();
		<c:forEach items="${carList }" var="car" varStatus="status">
		var index = <c:out value="${status.count}"/>;
		position4bound[(index-1)]=new daum.maps.LatLng(<c:out value="${car.lat}"/>, <c:out value="${car.lng}"/>)
		</c:forEach>
		
		// ? LatLngBounds ?? ??
		var bounds = new daum.maps.LatLngBounds();
		
		for(var i = 0; i < position4bound.length; i++)
		{
			bounds.extend(position4bound[i]);
		}
		try{
			var boundInterval = setInterval(function(){
				_daumMap.map.setBounds(bounds);
				
				relayout();
				
				window.clearInterval(boundInterval);
				
				},300);	
		}catch(e){}
		
		
// 		//logs('bounds 1111111111111111111111111111111');
	
	}
	
	function relayout(){
		_daumMap.map.relayout();
	}
	
	var selectedCar=0;
	function setDaumMapCenter(lat, lng, carCode, option){
		if(outOfKoreaRange(lat, lng)) return;
		logs('setDaumMapCenter');
		logs('lat'+lat+', lng='+lng+', carCode='+carCode);
		try{
			selectedCar = carCode;
			if(option){
				moveMapTo(lat, lng);	
			}
		}catch(e){
			logs('setDaumMapCenter error!!!!');			
			logs(e);
		}
		
	}
	
	function getDistanceFromLatLngInKm(lat1,lng1,lat2,lng2) {
		  var R = 6371; // Radius of the earth in km
		  var dLat = deg2rad(lat2-lat1);  // deg2rad below
		  var dLng = deg2rad(lng2-lng1); 
		  var a = 
		    Math.sin(dLat/2) * Math.sin(dLat/2) +
		    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * 
		    Math.sin(dLng/2) * Math.sin(dLng/2)
		    ; 
		  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
		  var d = R * c; // Distance in km
// 		  //logs('둘 사이의 거리.'+d*1000);
		  return d*1000;
		}
	
	
	/*
	목적지 그리기. m120에서 부른다.
	return marker array
	*/
	function makeDestiList(carDestList){
		logs('makeDestiList');
		logs(carDestList);
		
		if(!carDestList) return null;
		if(carDestList.length==0) return null;
		
		
		var markers = new Array();
		$(carDestList).each(function(){
			logs(this);
			
			var obj={
					lat:this.lat,
					lng:this.lng,
					imgNm:'destination_mark.png',
					title:this.name+'['+this.passed+']',
					point:'top'
			};
			
			// 마커 그리기
			markers.push(drawMarker(obj));
	
			
		});
		
		return markers;
	}
	
	
	/**
	* 관심지역 그리기
	호출하는 곳 m110, m120
	위경도, 크기(radius)를 받는다.
	*
	*/

	function makeCheckArea(checkAreaList){
		$(checkAreaList).each(function(){
			
			var obj={
					lat:this.lat,
					lng:this.lng,
					imgNm:'interest_mark.png',
					title:this.name+'['+this.address+']',
					radius:this.radius,
					point:'top',
					strokeColor:"#FF0000",
					fillColor:"#FF0000"
					
			};
			
			// 원 그리기
			drawCircle(obj);
			
			// 마커 그리기
			drawMarker(obj);
	
			
		});
	}
	
	/**
	마커 그리기
	param : lat, lng, imgNm : 이미지 파일 명
	title : 표시할 타이틀
	*/
	function drawMarker(obj){
		if(!obj) return null;
		
		var size={
				width:obj.width||25,
				height:obj.height||49
		};
		
		var point={
				x:size.width/2,
				y:size.height/2
		};
		if(obj.point){
			if(obj.point=='center'){
				
			}else if(obj.point=='top'){
				point.y=size.height;
			}else if(obj.point=='bottom'){
				point.y=0;
			}
		}
		
		// 마커 그리기.
		var marker_icon = new daum.maps.MarkerImage(
			'${imgUrl}/'+obj.imgNm,
			new daum.maps.Size(size.width, size.height),
			new daum.maps.Point(point.x,point.y),
			"poly",
			"1,20,1,9,5,2,10,0,21,0,27,3,30,9,30,20,17,33,14,33"
		);
		
		var marker_options = {
			position: new daum.maps.LatLng(obj.lat, obj.lng),
			image: marker_icon,
		                    title: obj.title,
		                    zIndex:'2'
		                    };
		var marker = new daum.maps.Marker(marker_options);
		marker.setMap(_daumMap.map);
		
		return marker;
	
	}
	
	/**
	* marker가 들어가 있는 array를 받아서 클리어 시킨다.
	*/
	function clearMarker(arr){
		
		if(!arr) return null;
		logs('clearMarker');
		logs('arr.length = '+arr.length);
		while(arr.length>0){
			var marker = arr.pop();
			try{
				marker.setMap(null);	
			}catch(e){}
			
		}
	}
	
	
	/**
	원그리기.
	param : lat, lng
	optional : strokeColor, fillColor, radius
	*/
	function drawCircle(obj){
		if(!obj) return null;
		var circle = null;
		try{
			circle = new daum.maps.Circle({
				center : new daum.maps.LatLng(obj.lat, obj.lng),
				radius : obj.radius||400,
				strokeWeight : 4,
				strokeColor : obj.strokeColor || "#1833e5",
				fillColor : obj.fillColor || "#1833e5",
				fillOpacity : 0.2
			});
			circle.setMap(_daumMap.map);	
		}catch(e){
			logs('drawCircle error!!');
			logs(e);
		}
		//원 그리기
		
		return circle;
	}
	
	
	
	
	

	function deg2rad(deg) {
	  return deg * (Math.PI/180);
	}
	
	/**
	* 위경도가 한국을 벗어나는지를 확인한다.
	* 벗어나면 true, 아니면 false;
	*
	*/
	function outOfKoreaRange(lat, lng){
		
		if(!lat||!lng) return true;	
		lng*=1;
		lat*=1;
		if(lng>lat){
			var tmp = lat;
			lat = lng;
			lng = tmp;
		}
		if(lat > 132 || lat<125 || lng > 39 || lng < 33) {
			logs('out of range!!!!!!!!!');
			return true;
		}
		return false;
		
// 		경위도상의 위치는 극동이 경상북도 울릉군의 독도(獨島)로 동경 131° 52′,
// 		극서가 전라남도 신안군의 소흑산도(小黑山島)로 동경 125° 04′, 
// 		극북이 강원도 고성군 현내면 송현진으로 북위 38° 27′, 
// 		극남이 제주도 남제주군 마라도(馬羅島)로 북위 33° 06′이다.
	
	}
	
</script>



</head>